package org.easyspring.util;

import org.springframework.cglib.beans.BeanCopier;
import org.springframework.cglib.beans.BeanMap;

import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author：hy
 * @date: 2024/6/24
 */
public class BeanCopierUtils {
    public static Map<String, BeanCopier> beanCopierMap = new HashMap<String,BeanCopier>();

    public static void copyProperties(Object source, Object target){
        String beanKey =  generateKey(source.getClass(), target.getClass());
        BeanCopier copier =  null;
        if(!beanCopierMap.containsKey(beanKey)){
            copier = BeanCopier.create(source.getClass(), target.getClass(), false);
            beanCopierMap.put(beanKey, copier);
        }else{
            copier = beanCopierMap.get(beanKey);
        }
        copier.copy(source, target, null);
    }

    private static String generateKey(Class<?> class1,Class<?>class2){
        return class1.toString() + class2.toString();
    }

    //对象转对象
    public static void bean2bean(Object bean1, Object bean2){
        BeanCopier beanCopier = BeanCopier.create(bean1.getClass(), bean2.getClass(), false);
        beanCopier.copy(bean1, bean2, null);
    }
    //对象转Map
    public static void bean2Map(Object bean1, Map<String, Object> map){
        Map<String, Object> beanMap = BeanMap.create(bean1);
        map.putAll(beanMap);
    }
    //Map转对象
    public static void map2Bean(Map<String, Object> map ,Object bean1){
        Map<String, Object> beanMap = BeanMap.create(bean1);
        beanMap.putAll(map);
    }

    public static void main(String[] args) {
        //对象转对象
        Test1VO test11 = getTest1();
        Test2VO test2 = new Test2VO();
        bean2bean(test11, test2);
        System.out.println(test2);

        //对象转Map
        Test1VO test1 = getTest1();
        Map<String, Object> map1 = new HashMap<>();
        bean2Map(test1, map1);
        System.out.println(map1);

        //Map转对象
        Map<String, Object> map = getMap();
        Test2VO test22 = new Test2VO();
        map2Bean(map, test22);
        System.out.println(test22);

    }

    private static Test1VO getTest1(){
        Test1VO test1 = new Test1VO();
        test1.setId(1);
        test1.setName("name");
        Map<String, String> attrs = new HashMap<>();
        attrs.put("key1", "value1");
        attrs.put("key2", "value2");
        test1.setAttrs(attrs);
        return test1;
    }

    private static Map<String, Object> getMap(){
        Map<String, Object> map = new HashMap<>();
        map.put("name", "This is name");
        map.put("id", 55);

        Map<String, String> attrs = new HashMap<>();
        attrs.put("key1", "value1");
        attrs.put("key2", "value2");
        map.put("attrs", attrs);
        return map;
    }
}
